package com.jeecms.cms.action.member;

import com.jeecms.cms.entity.assist.Branch;
import com.jeecms.cms.entity.assist.CmsConfigContentCharge;
import com.jeecms.cms.entity.assist.CmsEnterprise;
import com.jeecms.cms.entity.assist.CmsWebservice;
import com.jeecms.cms.manager.assist.CmsConfigContentChargeMng;
import com.jeecms.cms.manager.assist.CmsWebserviceMng;
import com.jeecms.cms.manager.main.CmsEnterpriseMng;
import com.jeecms.common.ipseek.PropertiesLoader;
import com.jeecms.common.security.encoder.Md5PwdEncoder;
import com.jeecms.common.web.RequestUtils;
import com.jeecms.common.web.session.SessionProvider;
import com.jeecms.common.web.springmvc.MessageResolver;
import com.jeecms.core.entity.*;
import com.jeecms.core.manager.CmsUserMng;
import com.jeecms.core.manager.UnifiedUserMng;
import com.jeecms.core.web.WebErrors;
import com.jeecms.core.web.util.CmsUtils;
import com.jeecms.core.web.util.FrontUtils;
import com.jeecms.plug.weixin.wxpay.WeixinOauth2Token;
import com.jeecms.plug.weixin.wxpay.utils.WeiXinConstants;
import com.jeecms.plug.weixin.wxpay.utils.WeixinUtil;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import static com.jeecms.cms.Constants.TPLDIR_CSI;
import static com.jeecms.cms.Constants.TPLDIR_MEMBER;

@Controller
public class LoginAct {
	public static final String LOGIN_CSI = "tpl.loginCsi";
	public static final String TPL_SPACE = "tpl.space";
	private static final String LOGIN_INPUT = "tpl.loginInput";
	private static final Logger log = LoggerFactory
			.getLogger(RegisterAct.class);
	/**
	 * 客户端包含
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login_csi.jspx")
	public String csi(HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		String ru = request.getParameter("returnUrl");
		boolean res=ru.contains("login.jspx") || ru.contains("register.jspx");
		if(!res){
			request.getSession().setAttribute("returnUrl",ru);
		}
		// 将request中所有参数
		model.putAll(RequestUtils.getQueryParams(request));
		FrontUtils.frontData(request, model, site);
		return FrontUtils.getTplPath(request, site.getSolutionPath(),
				TPLDIR_CSI, LOGIN_CSI);
	}

	/**
	 * 微信回调地址
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/wxlogin.jspx")
	public String wxlogin(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws UnsupportedEncodingException {

		HttpSession session = request.getSession();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		// 用户同意授权后，能获取到code
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		System.out.println("--------code：" + code + "-----state:" + state);
        CmsConfigContentCharge config=configContentChargeMng.getDefault();
		// 用户同意授权
		// 获取网页授权access_token
		WeixinOauth2Token weixinOauth2Token = WeixinUtil.getOauth2AccessToken(code, config);
		System.out.println("---------------weixinOauth2Token:" + weixinOauth2Token);
		// 网页授权接口访问凭证
		String accessToken = weixinOauth2Token.getAccessToken();
		// 用户标识
		String openId = weixinOauth2Token.getOpenId();
		//1.将用户登录信息放入session里
//		session.removeAttribute(WeiXinConstants.OPEN_ID);
//		session.setAttribute(WeiXinConstants.OPEN_ID, openId);
		CmsUser cmsUser = cmsUserMng.findByOpenId(openId);
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		if(cmsUser != null){
			model.addAttribute("username",cmsUser.getUsername());
			model.addAttribute("password1",cmsUser.getPassword1());
			return FrontUtils.getTplPath(request, site.getSolutionPath(),TPLDIR_MEMBER, "tpl.mobile_auto_login");
		}else{
			model.addAttribute("openid",openId);
			return FrontUtils.getTplPath(request, site.getSolutionPath(),TPLDIR_MEMBER, "tpl.mobile_register");
		}
	}

	/**
	 * 跳转入口
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/wxauth.jspx")
	public String wxauth(Integer id, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		CmsUser user = CmsUtils.getUser(request);
		//当前用户未登录
		if (user == null) {
			String equipment=(String) request.getAttribute("ua");
			//当前是手机用户
			if(StringUtils.isNotBlank(equipment)&&equipment.equals("mobile")){
				String host = "http://" + CmsUtils.getSite(request).getDomain();
				//根据活动id查询活动表，并得到跳转url后得到重定向地址
//        target_url = "/mobile/merchantuser/mypay";
				//根据活动对象id查询公众号信息,请求参数需要公众号信息
				HttpSession session = request.getSession();
				Object oi = session.getAttribute(WeiXinConstants.OPEN_ID);

				String scope = "snsapi_userinfo";
//				}
				//回调地址
				String url = host + "/wxlogin.jspx";
				String requestUrl = WeixinUtil.WEB_OAUTH_URL;
				CmsConfigContentCharge config=configContentChargeMng.getDefault();
				requestUrl = requestUrl.replace("APPID", config.getWeixinAppId());
				requestUrl = requestUrl.replace("REDIRECT_URI", this.getURLEncoderString(url));
				requestUrl = requestUrl.replace("CODE", "code");
				requestUrl = requestUrl.replace("SCOPE", scope);
				requestUrl = requestUrl.replace("STATE", "STATE");

				return "redirect:" + requestUrl;
			}else{
				return "redirect:/login.jspx";
			}
		}else{
			//已登录过的流转
			return null;
			//return playVideo(id, request, response, model);
		}
	}

	/**
	 * 微信绑定
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/wxbind.jspx")
	public String wxbind(String username, String password, String openid,HttpServletRequest request, ModelMap model) {
		String password1 =new Md5PwdEncoder().encodePassword(password);

//		List<CmsUser> cmsUsers = cmsUserMng.getListByUsernameAndPassword(username, password1);
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		UnifiedUser unifiedUser = unifiedUserMng.getByUsername(username);
		if(unifiedUser != null){
			String password2 = unifiedUser.getPassword();
			if(StringUtils.isNotBlank(password2)){
				CmsUser cmsUser = cmsUserMng.findByUsername(username);
				cmsUser.setOpenId(openid);
				cmsUser.setPassword1(password);
				cmsUserMng.updateUser(cmsUser);

				model.addAttribute("username",username);
				model.addAttribute("password1",password);
				return FrontUtils.getTplPath(request, site.getSolutionPath(),TPLDIR_MEMBER, "tpl.mobile_auto_login");
			}else{

			}
		}else{

		}

		return null;
	}

	/**
	 * 微信注册
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/wxregister.jspx")
	public String wxregister(String username, String invitationCode, String email, Integer branchId, String loginPassword, String smCode, String validateCode,
							 CmsUserExt userExt, String captcha, String nextUrl, String openid, HttpServletRequest request,HttpServletResponse response, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		CmsConfig config = site.getConfig();
		WebErrors errors = validateSubmit(username, invitationCode, loginPassword, captcha, smCode, validateCode,
				site, request, response);
		boolean disabled=false;
		if(config.getMemberConfig().isCheckOn()){
			disabled=true;
		}
		if (errors.hasErrors()) {
			return FrontUtils.showError(request, response, model, errors);
		}
		String ip = RequestUtils.getIpAddr(request);
		Map<String,String> attrs=RequestUtils.getRequestMap(request, "attr_");

		if(StringUtils.isNotBlank(invitationCode)) {
			userExt.setBranch(new Branch(branchId));
			//通过邀请码找到企业信息
			CmsEnterprise enterprise = cmsEnterpriseMng.getEnterpriseByInvitationCode(invitationCode);
			userExt.setEnterprise(enterprise);
			//注册成功后，将邀请码次数减1
			enterprise.setInvitationCount(enterprise.getInvitationCount() - 1);
			cmsEnterpriseMng.update(enterprise);
		}
		cmsUserMng.registerMember(username, email, loginPassword, ip, null,null,disabled,userExt,attrs,openid,loginPassword);
		cmsWebserviceMng.callWebService("false",username, loginPassword, "", userExt, CmsWebservice.SERVICE_TYPE_ADD_USER);
		log.info("member register success. username={}", username);
		FrontUtils.frontData(request, model, site);
		FrontUtils.frontPageData(request, model);
		model.addAttribute("success", true);
		return FrontUtils.getTplPath(request, site.getSolutionPath(),
				TPLDIR_MEMBER, LOGIN_INPUT);


//		String password1 =new Md5PwdEncoder().encodePassword(loginPassword);

//		List<CmsUser> cmsUsers = cmsUserMng.getListByUsernameAndPassword(username, password1);
//		CmsSite site = CmsUtils.getSite(request);
//		FrontUtils.frontData(request, model, site);
//		UnifiedUser unifiedUser = unifiedUserMng.getByUsername(username);
//		if(unifiedUser != null){
//			String password2 = unifiedUser.getPassword();
//			if(StringUtils.isNotBlank(password2)){
//				CmsUser cmsUser = cmsUserMng.findByUsername(username);
//				cmsUser.setOpenId(openid);
//				cmsUser.setPassword1(loginPassword);
//				cmsUserMng.updateUser(cmsUser);
//
//				model.addAttribute("username",username);
//				model.addAttribute("password1",loginPassword);
//				return FrontUtils.getTplPath(request, site.getSolutionPath(),TPLDIR_MEMBER, "tpl.mobile_auto_login");
//			}else{
//
//			}
//		}else{
//
//		}
//
//		return null;
	}

	private WebErrors validateSubmit(String username, String invitationCode,
									 String loginPassword, String captcha, String smCode, String validateCode, CmsSite site,
									 HttpServletRequest request, HttpServletResponse response) {
		MemberConfig mcfg = site.getConfig().getMemberConfig();
		WebErrors errors = WebErrors.create(request);
		try {
			if (!imageCaptchaService.validateResponseForID(session
					.getSessionId(request, response), captcha)) {
				errors.addErrorCode("error.invalidCaptcha");
				return errors;
			}
		} catch (CaptchaServiceException e) {
			errors.addErrorCode("error.exceptionCaptcha");
			log.warn("", e);
			return errors;
		}
		if (errors.ifOutOfLength(username, MessageResolver.getMessage(request, "field.username"),
				mcfg.getUsernameMinLen(), 100, true)) {
			return errors;
		}
		if (errors.ifNotUsername(username,MessageResolver.getMessage(request, "field.username"),
				mcfg.getUsernameMinLen(), 100, true)) {
			return errors;
		}
		if (errors.ifOutOfLength(loginPassword, MessageResolver.getMessage(request, "field.password"),
				mcfg.getPasswordMinLen(), 100, true)) {
			return errors;
		}
		//短信验证码
		if (!smCode.equalsIgnoreCase(validateCode) ){
			errors.addErrorCode("error.smCode", "smCode");
			return errors;
		}
		// 保留字检查不通过，返回false。
		if (!mcfg.checkUsernameReserved(username)) {
			errors.addErrorCode("error.usernameReserved");
			return errors;
		}
		// 用户名存在，返回false。
		if (unifiedUserMng.usernameExist(username)) {
			errors.addErrorCode("error.usernameExist");
			return errors;
		}
		return errors;
	}

    /**
     * URL 转码
     *
     * @return String
     * @author
     * @date
     */
    public String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

	@Autowired
	private CmsUserMng cmsUserMng;
	@Autowired
	private UnifiedUserMng unifiedUserMng;
	@Autowired
	private SessionProvider session;
	@Autowired
	private ImageCaptchaService imageCaptchaService;
	@Autowired
	private CmsWebserviceMng cmsWebserviceMng;
	@Autowired
	private CmsEnterpriseMng cmsEnterpriseMng;
    @Autowired
    private CmsConfigContentChargeMng configContentChargeMng;

}
